/* 购物车页面逻辑 */
class CartPageManager {
    constructor() {
        this.cartItems = [];
        this.selectedItems = new Set();
        this.currentDiscount = 0;
        this.init();
    }

    init() {
        this.bindEvents();
        this.loadCartItems();
    }

    bindEvents() {
        // 全选/取消全选
        document.getElementById('selectAllBtn').addEventListener('click', this.selectAll.bind(this));
        document.getElementById('deselectAllBtn').addEventListener('click', this.deselectAll.bind(this));
        
        // 清空购物车
        document.getElementById('clearCartBtn').addEventListener('click', this.showClearCartConfirm.bind(this));
        
        // 结算
        document.getElementById('checkoutBtn').addEventListener('click', this.proceedToCheckout.bind(this));
        
        // 玩折扣游戏
        document.getElementById('playGameBtn').addEventListener('click', this.playDiscountGame.bind(this));
        
        // 确认模态框
        document.getElementById('closeConfirmModal').addEventListener('click', this.hideConfirmModal.bind(this));
        document.getElementById('cancelConfirm').addEventListener('click', this.hideConfirmModal.bind(this));
        document.getElementById('confirmAction').addEventListener('click', this.executeConfirmAction.bind(this));
        
        // 点击模态框外部关闭
        document.getElementById('confirmModal').addEventListener('click', (e) => {
            if (e.target.id === 'confirmModal') {
                this.hideConfirmModal();
            }
        });
    }

    loadCartItems() {
        // 等待cartManager初始化完成
        if (window.cartManager) {
            this.cartItems = window.cartManager.items;
            this.selectedItems = new Set();
            
            // 恢复选中状态
            this.cartItems.forEach(item => {
                if (item.selected) {
                    this.selectedItems.add(item.product_id);
                }
            });
            
            this.renderCartItems();
            this.updateSummary();
        } else {
            // 如果cartManager还没加载，延迟重试
            setTimeout(() => {
                this.loadCartItems();
            }, 100);
        }
    }

    renderCartItems() {
        const cartItemsContainer = document.getElementById('cartItems');
        const emptyCart = document.getElementById('emptyCart');
        const cartContent = document.getElementById('cartContent');
        
        if (this.cartItems.length === 0) {
            emptyCart.style.display = 'block';
            cartContent.style.display = 'none';
            return;
        }
        
        emptyCart.style.display = 'none';
        cartContent.style.display = 'block';
        
        cartItemsContainer.innerHTML = this.cartItems.map(item => this.createCartItemHTML(item)).join('');
        
        // 绑定商品操作事件
        this.bindItemEvents();
    }

    createCartItemHTML(item) {
        const isSelected = this.selectedItems.has(item.product_id);
        
        return `
            <div class="cart-item" data-product-id="${item.product_id}">
                <div class="item-checkbox">
                    <input type="checkbox" id="item-${item.product_id}" ${isSelected ? 'checked' : ''}>
                    <label for="item-${item.product_id}"></label>
                </div>
                
                <div class="item-image">
                    <img src="https://via.placeholder.com/100x100?text=${encodeURIComponent(item.product_name)}" 
                         alt="${item.product_name}" 
                         onerror="this.src='https://via.placeholder.com/100x100?text=商品图片'">
                </div>
                
                <div class="item-info">
                    <h3 class="item-name">
                        <a href="product-detail.html?id=${item.product_id}">${item.product_name}</a>
                    </h3>
                    <div class="item-price">¥${item.price.toFixed(2)}</div>
                </div>
                
                <div class="item-quantity">
                    <div class="quantity-controls">
                        <button class="quantity-btn decrease" data-product-id="${item.product_id}">-</button>
                        <input type="number" 
                               class="quantity-input" 
                               value="${item.quantity}" 
                               min="1" 
                               max="99"
                               data-product-id="${item.product_id}">
                        <button class="quantity-btn increase" data-product-id="${item.product_id}">+</button>
                    </div>
                </div>
                
                <div class="item-total">
                    <span class="total-price">¥${(item.price * item.quantity).toFixed(2)}</span>
                </div>
                
                <div class="item-actions">
                    <button class="btn btn-outline btn-sm remove-item" data-product-id="${item.product_id}">
                        <i class="fas fa-trash"></i>
                        删除
                    </button>
                </div>
            </div>
        `;
    }

    bindItemEvents() {
        // 商品选择
        document.querySelectorAll('.cart-item input[type="checkbox"]').forEach(checkbox => {
            checkbox.addEventListener('change', (e) => {
                const productId = e.target.id.replace('item-', '');
                this.toggleItemSelection(productId);
            });
        });

        // 数量控制
        document.querySelectorAll('.quantity-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const productId = e.target.dataset.productId;
                const isIncrease = e.target.classList.contains('increase');
                this.updateQuantity(productId, isIncrease);
            });
        });

        document.querySelectorAll('.quantity-input').forEach(input => {
            input.addEventListener('change', (e) => {
                const productId = e.target.dataset.productId;
                const quantity = parseInt(e.target.value);
                this.setQuantity(productId, quantity);
            });
        });

        // 删除商品
        document.querySelectorAll('.remove-item').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const productId = e.target.closest('.remove-item').dataset.productId;
                this.showRemoveItemConfirm(productId);
            });
        });
    }

    toggleItemSelection(productId) {
        if (this.selectedItems.has(productId)) {
            this.selectedItems.delete(productId);
        } else {
            this.selectedItems.add(productId);
        }
        
        // 更新购物车管理器
        if (window.cartManager) {
            window.cartManager.toggleSelection(productId);
        }
        
        this.updateSummary();
    }

    updateQuantity(productId, isIncrease) {
        const item = this.cartItems.find(item => item.product_id === productId);
        if (!item) return;
        
        if (isIncrease) {
            item.quantity = Math.min(item.quantity + 1, 99);
        } else {
            item.quantity = Math.max(item.quantity - 1, 1);
        }
        
        // 更新购物车管理器
        if (window.cartManager) {
            window.cartManager.updateQuantity(productId, item.quantity);
        }
        
        this.renderCartItems();
        this.updateSummary();
    }

    setQuantity(productId, quantity) {
        if (quantity < 1 || quantity > 99) {
            this.renderCartItems();
            return;
        }
        
        const item = this.cartItems.find(item => item.product_id === productId);
        if (!item) return;
        
        item.quantity = quantity;
        
        // 更新购物车管理器
        if (window.cartManager) {
            window.cartManager.updateQuantity(productId, quantity);
        }
        
        this.updateSummary();
    }

    selectAll() {
        this.selectedItems.clear();
        this.cartItems.forEach(item => {
            this.selectedItems.add(item.product_id);
            item.selected = true;
        });
        
        // 更新购物车管理器
        if (window.cartManager) {
            window.cartManager.selectAll();
        }
        
        this.renderCartItems();
        this.updateSummary();
    }

    deselectAll() {
        this.selectedItems.clear();
        this.cartItems.forEach(item => {
            item.selected = false;
        });
        
        // 更新购物车管理器
        if (window.cartManager) {
            window.cartManager.deselectAll();
        }
        
        this.renderCartItems();
        this.updateSummary();
    }

    updateSummary() {
        const selectedItems = this.cartItems.filter(item => this.selectedItems.has(item.product_id));
        const selectedCount = selectedItems.length;
        const subtotal = selectedItems.reduce((total, item) => total + (item.price * item.quantity), 0);
        
        // 计算运费（简化计算）
        const shippingFee = selectedCount > 0 ? 15.00 : 0;
        const totalAmount = subtotal + shippingFee - (subtotal * this.currentDiscount / 100);
        
        // 更新UI
        document.getElementById('selectedCount').textContent = selectedCount;
        document.getElementById('subtotal').textContent = `¥${subtotal.toFixed(2)}`;
        document.getElementById('shippingFee').textContent = `¥${shippingFee.toFixed(2)}`;
        document.getElementById('totalAmount').textContent = `¥${totalAmount.toFixed(2)}`;
        
        // 更新结算按钮状态
        const checkoutBtn = document.getElementById('checkoutBtn');
        checkoutBtn.disabled = selectedCount === 0;
        
        // 显示折扣信息
        if (this.currentDiscount > 0) {
            this.showDiscountInfo();
        }
    }

    showDiscountInfo() {
        const subtotal = this.cartItems
            .filter(item => this.selectedItems.has(item.product_id))
            .reduce((total, item) => total + (item.price * item.quantity), 0);
        
        const discountAmount = subtotal * this.currentDiscount / 100;
        
        // 添加折扣显示
        let discountElement = document.getElementById('discountInfo');
        if (!discountElement) {
            discountElement = document.createElement('div');
            discountElement.id = 'discountInfo';
            discountElement.className = 'summary-item discount';
            document.querySelector('.summary-content').appendChild(discountElement);
        }
        
        discountElement.innerHTML = `
            <span class="label">游戏折扣：</span>
            <span class="value discount-amount">-¥${discountAmount.toFixed(2)}</span>
        `;
    }

    proceedToCheckout() {
        if (this.selectedItems.size === 0) {
            this.showNotification('请选择要购买的商品', 'error');
            return;
        }
        
        if (!window.authManager.isAuthenticated()) {
            window.authManager.showLoginModal();
            return;
        }
        
        // 保存选中的商品到localStorage，供结算页面使用
        const selectedItems = this.cartItems.filter(item => this.selectedItems.has(item.product_id));
        localStorage.setItem('checkoutItems', JSON.stringify(selectedItems));
        
        console.log('准备结算的商品:', selectedItems);
        
        // 跳转到结算页面
        const discountParam = this.currentDiscount > 0 ? `?discount=${this.currentDiscount}` : '';
        window.location.href = `checkout.html${discountParam}`;
    }

    playDiscountGame() {
        if (!window.authManager.isAuthenticated()) {
            window.authManager.showLoginModal();
            return;
        }
        
        if (window.discountGame) {
            window.discountGame.showGameModal();
        }
    }

    showClearCartConfirm() {
        this.showConfirmModal(
            '确定要清空购物车吗？',
            () => {
                if (window.cartManager) {
                    window.cartManager.clearCart();
                }
                this.cartItems = [];
                this.selectedItems.clear();
                this.renderCartItems();
                this.updateSummary();
                this.showNotification('购物车已清空', 'success');
            }
        );
    }

    showRemoveItemConfirm(productId) {
        const item = this.cartItems.find(item => item.product_id === productId);
        const productName = item ? item.product_name : '商品';
        
        this.showConfirmModal(
            `确定要删除"${productName}"吗？`,
            () => {
                this.removeItem(productId);
            }
        );
    }

    removeItem(productId) {
        // 从购物车管理器移除
        if (window.cartManager) {
            window.cartManager.removeFromCart(productId);
        }
        
        // 从本地数组移除
        this.cartItems = this.cartItems.filter(item => item.product_id !== productId);
        this.selectedItems.delete(productId);
        
        this.renderCartItems();
        this.updateSummary();
        this.showNotification('商品已删除', 'success');
    }

    showConfirmModal(message, callback) {
        const modal = document.getElementById('confirmModal');
        const messageElement = document.getElementById('confirmMessage');
        const confirmBtn = document.getElementById('confirmAction');
        
        messageElement.textContent = message;
        modal.style.display = 'block';
        document.body.style.overflow = 'hidden';
        
        // 移除之前的事件监听器
        const newConfirmBtn = confirmBtn.cloneNode(true);
        confirmBtn.parentNode.replaceChild(newConfirmBtn, confirmBtn);
        
        // 添加新的事件监听器
        newConfirmBtn.addEventListener('click', () => {
            callback();
            this.hideConfirmModal();
        });
    }

    hideConfirmModal() {
        const modal = document.getElementById('confirmModal');
        modal.style.display = 'none';
        document.body.style.overflow = 'auto';
    }

    executeConfirmAction() {
        // 这个方法会被动态替换的事件监听器调用
    }

    async loadRecommendedProducts() {
        try {
            const result = await window.productManager.getRecommendedProducts();
            if (result.success) {
                const container = document.getElementById('recommendedProducts');
                if (container) {
                    window.productManager.renderProductGrid(container, result.data.slice(0, 4));
                }
            }
        } catch (error) {
            console.error('加载推荐商品失败:', error);
        }
    }

    showNotification(message, type = 'info') {
        if (window.authManager && window.authManager.showNotification) {
            window.authManager.showNotification(message, type);
        }
    }

    // 应用折扣（从游戏获得）
    applyDiscount(discountPercent) {
        this.currentDiscount = discountPercent;
        this.updateSummary();
        this.showNotification(`成功获得 ${discountPercent}% 折扣！`, 'success');
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    // 延迟初始化，确保所有模块都已加载
    setTimeout(() => {
        window.cartPageManager = new CartPageManager();
        
        // 如果用户已登录，尝试从后端加载购物车数据
        if (window.authManager && window.authManager.isAuthenticated()) {
            loadCartFromBackend();
        }
        
        // 加载推荐商品
        window.cartPageManager.loadRecommendedProducts();
        
        // 监听折扣游戏结果
        if (window.discountGame) {
            // 重写折扣游戏的applyDiscount方法
            const originalApplyDiscount = window.discountGame.applyDiscount;
            window.discountGame.applyDiscount = function(discountPercent) {
                originalApplyDiscount.call(this, discountPercent);
                if (window.cartPageManager) {
                    window.cartPageManager.applyDiscount(discountPercent);
                }
            };
        }
    }, 200);
    
    // 从后端加载购物车数据
    async function loadCartFromBackend() {
        try {
            if (window.api && window.cartManager) {
                const result = await window.api.getCart();
                if (result.success && result.data.items) {
                    // 更新cartManager的数据
                    window.cartManager.items = result.data.items;
                    window.cartManager.selectedItems.clear();
                    window.cartManager.items.forEach(item => {
                        if (item.selected) {
                            window.cartManager.selectedItems.add(item.product_id);
                        }
                    });
                    
                    // 更新购物车页面显示
                    if (window.cartPageManager) {
                        window.cartPageManager.loadCartItems();
                    }
                    
                    console.log('从后端加载购物车数据成功:', result.data.items);
                }
            }
        } catch (error) {
            console.warn('从后端加载购物车数据失败:', error);
        }
    }
});
